
import 'dart:async';

import 'package:flutter_wan_android/api/api_server.dart';
import 'package:flutter_wan_android/bean/project_list_bean.dart';
import 'package:flutter_wan_android/bean/project_tree_bean.dart';
import 'package:flutter_wan_android/blocs/base/bloc_provider.dart';
import 'package:rxdart/rxdart.dart';

class ProjectTreeBloc extends BaseBloc{
  BehaviorSubject<List<ProjectTreeBean>> _subject = BehaviorSubject();

  Stream<List<ProjectTreeBean>> get stream => _subject.stream;

  StreamSubscription<List<ProjectTreeBean>> _streamSubscription;



  BehaviorSubject<List<ProjectItem>> _listSubject=BehaviorSubject();
  Stream<List<ProjectItem>> get listStream => _listSubject.stream;
  List<ProjectItem> _allData=[];
  List<ProjectItem> get allData =>_allData;
  StreamSubscription<List<ProjectItem>> _listStreamSubscription;



  Future getProjectList(pageIndex,cid) async{
    return await ApiServer.getProjectList(pageIndex,cid: cid).then((item){

      if(_allData.length>0 && pageIndex==0){
        _listSubject.sink.add(item.datas);
        return;
      }
      _allData.addAll(item.datas);
      _listSubject.sink.add(item.datas);

    }).catchError((error){
      _subject.sink.addError(error);
    });
  }


  Future getProjectTree() async {
    if (_streamSubscription == null) {
      _streamSubscription = _subject.listen((data) {});
    }else{
      if(_streamSubscription.isPaused){
        resumeProjectStream();
      }
    }
    return await ApiServer.getProjectTree().then((list) {
      _subject.sink.add(list);
    }).catchError((error) => _subject.sink.addError(error));
  }

  @override
  void dispose() {
    _subject.close();
    _listSubject.close();
  }

  void pauseProjectStream() {
    if (_streamSubscription != null) {
      _streamSubscription.pause();
    }
  }

  void resumeProjectStream(){
    if (_streamSubscription != null) {
      _streamSubscription.resume();
    }
  }

}